package yannan.voiplock4ble.fragment;


import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import yannan.voiplock4ble.R;
import yannan.voiplock4ble.adapter.LockRecordAdapter;
import yannan.voiplock4ble.adapter.base.IMyOnScrollListener;
import yannan.voiplock4ble.adapter.base.IOnRecyclerLoading;
import yannan.voiplock4ble.base.Content;
import yannan.voiplock4ble.base.LockBaseFragment;
import yannan.voiplock4ble.base.MyApplication;
import yannan.voiplock4ble.bean.LockBean;
import yannan.voiplock4ble.bean.LockRecordBean;
import yannan.voiplock4ble.db.DaoUtils;
import yannan.voiplock4ble.db.MyDBHelper;
import yannan.voiplock4ble.db.daomanager.LockRecordDaoManager;
import yannan.voiplock4ble.eventbus.BaseEventMsg;
import yannan.voiplock4ble.eventbus.ConnectFailedMsg;
import yannan.voiplock4ble.eventbus.UnlockRecordMsg;
import yannan.voiplock4ble.net.NetUtils;
import yannan.voiplock4ble.net.base.NetworkCallBack;
import yannan.voiplock4ble.service.ble.BleOperUtils;
import yannan.voiplock4ble.service.ble.BleService;
import yannan.voiplock4ble.service.ble.BleUtils;
import yannan.voiplock4ble.task.UpOrDownLockRecordTask;
import yannan.voiplock4ble.utils.LogUtils;
import yannan.voiplock4ble.utils.TimeUtils;
import yannan.voiplock4ble.view.RecyclerSupportViewEmpty;

/**
 * 说明：开锁记录
 * 作者：mainTel
 * 时间：2016/8/24 09:39
 * 备注：
 */
@Content(R.layout.fragment_lock_record)
public class LockRecordFragment extends LockBaseFragment implements SwipeRefreshLayout.OnRefreshListener, IOnRecyclerLoading, IMyOnScrollListener {

    @Bind(R.id.swipe_content)
    SwipeRefreshLayout swipe_content;
    @Bind(R.id.lv_lock_record)
    RecyclerSupportViewEmpty lv_lock_record;
    @Bind(R.id.lv_lock_record_empty_view)
    ScrollView emptyView;
    @Bind(R.id.lv_lock_record_empty_textview)
    TextView lv_lock_record_empty_textview;
    @Bind(R.id.ll_head_title)
    LinearLayout ll_head_title;
    @Bind(R.id.tv_head_title)
    TextView tv_head_title;
    @Bind(R.id.iv_blue_icon)
    ImageView iv_blue_icon;
    LockRecordAdapter adapter;
    LockRecordDaoManager lockRecordBeanDao;
    LockBean nowLock;
    int pageIndex;
    boolean isHidden;

    @Override
    public void initdata() {
        swipe_content.setOnRefreshListener(this);
        adapter = new LockRecordAdapter(new ArrayList<LockRecordBean>(), mContext, lv_lock_record);
        adapter.setMyOnScrollListener(this);
        adapter.setOnRecyclerLoading(this);
        lockRecordBeanDao = DaoUtils.getDao(LockRecordDaoManager.class);
        lv_lock_record_empty_textview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!swipe_content.isRefreshing()) {
                    swipe_content.setRefreshing(true);
                    getLockRecord();
                }
            }
        });
    }

    @Override
    public void initView() {
        swipe_content.setColorSchemeResources(R.color.color_04bfad_gray, R.color.color_04bfad, R.color.color_04bfad_drak);
        lv_lock_record.setLayoutManager(new LinearLayoutManager(mContext));
        lv_lock_record.setEmptyView(emptyView);
        lv_lock_record.setAdapter(adapter);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("LockRecordFragment");
        if (!isHidden)
            checkAndLoadData();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("LockRecordFragment");
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventMsg msg) {
        if (msg instanceof UnlockRecordMsg) {
            UnlockRecordMsg unlockRecordMsg = (UnlockRecordMsg) msg;
            if (unlockRecordMsg.isNew) {

            } else if (unlockRecordMsg.type == 1) {
                mHandler.removeMessages(GET_UNLOCK_RECORD_TIMEER);
                mHandler.removeMessages(GET_UNLOCK_RECORD_TIMEER_REFRESH);
                mHandler.sendEmptyMessageDelayed(GET_UNLOCK_RECORD_TIMEER, 2000);
            }
        } else if (msg instanceof ConnectFailedMsg) {
            ConnectFailedMsg connectFailedMsg = (ConnectFailedMsg) msg;
            LogUtils.i("LockKeyPwdFragment==" + connectFailedMsg.isConnect);
            if (connectFailedMsg.isConnect) {
                MyApplication.getInterface().isHaveConnected = true;
                iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_connected);
                nowLock=mainActivity.lockBeanNow;
                getLockRecord();
            } else {
                MyApplication.getInterface().isHaveConnected = false;
                iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_disconnect);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String msg) {
        if (msg.equals("UpOrDownLockRecordTask_update")) {
            loadLockRecord();
        } else if (msg.equals("cancelRecordRefresh")) {
            swipe_content.setRefreshing(false);
        } else if (msg.equals("changeLockMsg")) {
            adapter.clear();
        }
    }

    private List<LockRecordBean> loadLockRecord() {

        List<LockRecordBean> list = MyDBHelper.getLockRedordList(nowLock.lockserialId);
        adapter.upDate(list);
        if (list.size() == 0) {
            ll_head_title.setVisibility(View.GONE);
        } else {
            ll_head_title.setVisibility(View.VISIBLE);
            tv_head_title.setText(list.get(0).unlockingDate.split(" ")[0]);
        }
        adapter.loadComplete();
        return list;
    }

    /**
     * 无论什么情况下 ，肯定是首先读取本地的数据
     */
    private void getLockRecord() {
        swipe_content.setRefreshing(true);
        //首先读取本地
        List<LockRecordBean> list = loadLockRecord();
        // TODO: 2016/11/30 如果在连接状态 获取门锁最新数据
        if (BleOperUtils.checkBleConnect(nowLock)) {
            //获取门锁数据
//            int startTime = 0;
            adapter.loadNoMore();
            int startTime = (int) (TimeUtils.getStr2Time1("2016-01-01 00:00:00") / 1000);
            if (list.size() != 0) {
                startTime = (int) (TimeUtils.getStr2Time1(list.get(0).unlockingDate) / 1000) + 2;
            }
            int endTime = (int) (TimeUtils.getNowTimeLong() / 1000);
//            long endTime = Long.MAX_VALUE;
            BleService.getBleService().sendOrder(BleUtils.getUnlockRecord(
                    MyApplication.getInterface().mConnectLock.contentToken,
                    startTime,
                    endTime));
            iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_connected);
            LogUtils.i("门锁记录链接门锁");
        } else {
            iv_blue_icon.setBackgroundResource(R.drawable.ic_bluetooth_disconnect);
            LogUtils.i("门锁记录断开门锁");
            if (list.size() != 0) {
                UpOrDownLockRecordTask.create(nowLock.lockserialId, adapter.getItemByPosition(0).unlockingDate).start();
            } else {
                UpOrDownLockRecordTask.create(nowLock.lockserialId, "0").start();
            }
        }
        swipe_content.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
//        mHandler.sendEmptyMessageDelayed(GET_UNLOCK_RECORD_TIMEER_REFRESH, 8000);
        getLockRecord();
    }

    @Override
    public void onRecyclerLoading(boolean isReloading) {
        getLockRecordNet(false);
    }

    /**
     * 获取从1970年到当前最后一条数据时间的开锁记录
     * 从网络获取开锁记录
     */
    private void getLockRecordNet(boolean isRefresh) {
        String time = "";
        if (adapter.list.size() != 0) {
            time = TimeUtils.getMinishTime(adapter.getItemByPosition(adapter.getItemCount() - 2).unlockingDate);
        } else {
            time = TimeUtils.getNowTimeyMdHMS();
        }
        if (MyApplication.getInterface().userBean != null)
            NetUtils.getNetworkService().getUnlockingRecord(
                    MyApplication.getInterface().userBean.userId,
                    "2016-01-01 00:00:00",
                    time,
                    pageIndex + "",
                    "30",
                    nowLock.lockserialId
            ).enqueue(new NetworkCallBack<List<LockRecordBean>>() {
                @Override
                public void onSuc(List<LockRecordBean> resBody) {
                    if (resBody != null && resBody.size() != 0) {
                        adapter.addUpDate(resBody);
                        DaoUtils.getDao(LockRecordDaoManager.class).insertOrReplaceList(resBody);
                        adapter.loadComplete();
                    } else {
                        adapter.loadNoMore();
                    }
                }

                @Override
                public void onFail(String msg) {
                    if (com.yongchun.library.BuildConfig.DEBUG) Log.e("LockRecordFragment", "获取失败");
                    adapter.loadError();
                }
            });
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {

    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        View stickyInfoView = recyclerView.findChildViewUnder(
                ll_head_title.getMeasuredWidth() / 2, 5);
        if (stickyInfoView != null && stickyInfoView.getContentDescription() != null) {
            tv_head_title.setText(String.valueOf(stickyInfoView.getContentDescription()));
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        isHidden = hidden;
        if (!hidden) {
            checkAndLoadData();
        }
    }

    private void checkAndLoadData() {
        if (nowLock != null) {
            if (!nowLock.lockserialId.equals(mainActivity.lockBeanNow.lockserialId)) {
                nowLock = mainActivity.lockBeanNow;
                getLockRecord();
            }
        } else {
            nowLock = mainActivity.lockBeanNow;
            getLockRecord();
        }
    }

    static final int GET_UNLOCK_RECORD_TIMEER = 1003;
    static final int GET_UNLOCK_RECORD_TIMEER_REFRESH = 1004;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case GET_UNLOCK_RECORD_TIMEER:
                    adapter.loadNoMore();
                    loadLockRecord();
                    swipe_content.setRefreshing(false);
                    try {
                        UpOrDownLockRecordTask.create(nowLock.lockserialId, adapter.getItemByPosition(0).unlockingDate).start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case GET_UNLOCK_RECORD_TIMEER_REFRESH:
                    swipe_content.setRefreshing(false);
                    break;
            }
        }
    };


}
